import { useUserStore } from '@/store/user';
import utils from '@/utils/utils.js';

export default {
	request(options = {}) {
		return new Promise((resolve, reject) => {

			const userStore = useUserStore();

			if (userStore.token) {
				options.header.Authorization = userStore.token;
			}

			options.complete = (response) => {
				if (response.statusCode == 200) {
					let code = response.data.code;

					if (code == 400) {
						setTimeout(() => {
							uni.showToast({
								title: response.data.message,
								icon: "none"
							}, 500);
						})
					}

					if (code == 2001) {
						userStore.logout();
						utils.doLogin()
					}

					resolve(response.data)
				} else {
					uni.showToast({
						title: response.data.msg,
						icon: "none"
					});
				}
			}

			uni.request(options)
		})
	},

	post(url, data = {}, header = {}) {

		let options = {
			url: url,
			data: data,
			header: header,
			method: "POST"
		}

		return this.request(options);
	},

	get(url, data = {}, header = {}) {
		let options = {
			url: url,
			data: data,
			header: header
		}

		return this.request(options);
	}
};